package WaitNotify.demo2;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2022-12-25
 * Time: 14:03
 */
public class GuardedObject {

    private Object response;

    //获取结果
    public Object get(long timeout) throws InterruptedException {
        synchronized (this) {
            long begin = System.currentTimeMillis();
            //从开始到现在经过的时间
            long passTime = 0;
            while (response==null) {
                //一轮的等待时间
                long waitTime = timeout-passTime;
                if(waitTime<=0) {
                    break;
                }
                this.wait(waitTime);
                passTime = System.currentTimeMillis() - begin;
            }
            return this.response;
        }
    }

    //产生结果
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

}
